package net.mthotel.web;

/**
 * Created by dengry on 15/3/21.
 */


import net.mthotel.entity.User;
import net.mthotel.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

@Controller
public class UserController {
    Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    UserService userService;

    @RequestMapping("/simple")
    public ModelAndView handleRequest(@RequestParam String username, @RequestParam String password) {
        log.debug("username:" + username + "|password:" + password);
        boolean f = userService.getUserByUsernameAndPassword(username, password);

        if (f) {
            return new ModelAndView("simple");
        } else {
            return new ModelAndView("err");
        }
    }

    @RequestMapping("/checkNameIsUse")
    public void checkNameIsUse(@RequestParam String username, HttpServletResponse response) throws IOException {
        log.debug("username:" + username);
        boolean f = userService.getUserByUsername(username);
        response.getWriter().print(f);
    }

    @RequestMapping("/checkVerifycode")
    public void checkVerifycode(@RequestParam String verifycode, HttpServletRequest request, HttpServletResponse response) throws IOException{
        log.debug("verifycode:" + verifycode);
        HttpSession session = request.getSession();
        String randomCode = (String) session.getAttribute("randomCode");
        if(verifycode.equals(randomCode)){
            response.getWriter().print(true);
        }else{
            response.getWriter().print(false);
        }
    }

    @RequestMapping("/addUser")
    public ModelAndView reg(@ModelAttribute User user){
        log.debug("credentialsType:"+user.getCredentialsType());
        userService.saveUser(user);
        return new ModelAndView("reg_success");
    }
    @RequestMapping("/toReg")
    public ModelAndView toReg(){
    	return new ModelAndView("reg");
    }
    
    @RequestMapping("/toMenu1")
    public ModelAndView toMenu1(){
    	return new ModelAndView("menu");
    }


    private static int WIDTH = 70;//设置图片的宽度
    private static int HEIGHT = 25;//设置图片的高度

    @RequestMapping("/getRandomCode")
    public void getRandomCode(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
        HttpSession session = request.getSession();
        response.setContentType("image/jpeg");
        ServletOutputStream sos = response.getOutputStream();

        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        char[] rands = generateCheckCode();
        drawBackground(g);
        drawRands(g, rands);
        g.dispose();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image, "JPEG", bos);
        byte[] buf = bos.toByteArray();
        response.setContentLength(buf.length);
        sos.write(buf);
        bos.close();
        sos.close();
        session.setAttribute("randomCode", new String(rands));
    }

    private void drawBackground(Graphics g) {
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, WIDTH, HEIGHT);
        for (int i = 0; i < 120; i++) {
            int x = (int) (Math.random() * WIDTH);
            int y = (int) (Math.random() * HEIGHT);
            int red = (int) (Math.random() * 255);
            int green = (int) (Math.random() * 255);
            int blue = (int) (Math.random() * 255);
            g.setColor(new Color(red, green, blue));
            g.drawOval(x, y, 1, 0);
        }
    }

    private void drawRands(Graphics g, char[] rands) {
        Random random = new Random();
        int red = random.nextInt(110);
        int green = random.nextInt(50);
        int blue = random.nextInt(50);
        g.setColor(new Color(red, green, blue));
        g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 22));
        g.drawString("" + rands[0], 3, 23);
        g.drawString("" + rands[1], 20, 23);
        g.drawString("" + rands[2], 35, 23);
        g.drawString("" + rands[3], 50, 23);
    }

    private char[] generateCheckCode() {
        String chars = "0123456789";
        char[] rands = new char[4];
        for (int i = 0; i < 4; i++) {
            int rand = (int) (Math.random() * 10);
            rands[i] = chars.charAt(rand);
        }
        return rands;
    }
    
    
}
